import passport from 'koa-passport'
import { Strategy } from 'passport-local'

import { Admin } from '../models'
import { errCode } from '../utils/common'
passport.serializeUser((admin, done) => {
    done(null, admin.id)
})

passport.deserializeUser(
    async(id, done) => {
        try {
            const admin = await Admin.findOne({ 'id': id })
            done(null, admin)
        } catch (err) {
            done(err)
        }
    })

passport.use('local', new Strategy({ usernameField: 'username', passwordField: 'password' },
    async(username, password, done) => {
        try {
            const admin = await Admin.findOne({ where: { 'username': username } })
            if (!admin) {
                return done(null, errCode.ERROR_ADMIN_NOTFOUND)
            }

            try {
                const isMatch = await admin.validatePassword(password)
                if (!isMatch) {
                    return done(null, errCode.ERROR_ADMIN_PASSWORD)
                }
                if (admin.status == 0) {
                    return done(null, errCode.ERROR_ADMIN_STATUS)
                }
                if (admin.status == 2) {
                    return done(null, errCode.ERROR_ADMIN_DELETE)
                }
                done(null, { code: 0, data: admin })
            } catch (err) {
                done(err)
            }
        } catch (err) {
            return done(err)
        }
    }
))